package com.yuji.aacar.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;

import com.yuji.aacar.net.config.BlueLog;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;


public class BitmapUtils {

    private final static float DEFAULT_IMAGE_WIDTH = 800f;
    private final static float DEFAULT_IMAGE_HEIGHT = 600f;
    public static float imgWidth;
    public static float imgHeight;

    /**
     * 读取图片 by assets
     *
     * @param context
     * @param path
     * @return
     */
    public static Bitmap getBitmapByAssets(Context context, String path) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = context.getResources().getAssets().open(path);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
        } finally {
            try {
                if (null != in) {
                    in.close();
                    in = null;
                }
            } catch (Exception ex) {

            }
        }
        return bitmap;
    }

    /**
     * 读取图片 by resouces
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap getBitmapByResource(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    public static final Bitmap readBitmapFromPath(String path)
            throws FileNotFoundException {
        Bitmap bitmap = null;
        InputStream is = new FileInputStream(new File(path));
        if (null != is) {
            try {
                byte[] data = readStream(is);
                bitmap = getBitmap(data, 768 * 768);
                float srcWidth = bitmap.getWidth();
                float srcHeight = bitmap.getHeight();
                // scale = (float) srcWidth / srcHeight;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    is = null;
                }
            }
        }

        return bitmap;
    }

    // 将byte转换成图片
    public static Bitmap getBitmap(byte[] data, int maxPixls) {
        // TODO Auto-generated method stub
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, opts);

        if (maxPixls <= 0) {
            maxPixls = 384 * 384;
        }

        opts.inSampleSize = computeSampleSize(opts, -1, maxPixls);
        opts.inJustDecodeBounds = false;
        try {
            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length,
                    opts);
            return bmp;
        } catch (OutOfMemoryError err) {
            err.printStackTrace();
        }
        return null;
    }

    // 读取字节流
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        inStream.close();
        return outstream.toByteArray();
    }

    /**
     * 备份图片
     *
     * @param fromPath
     * @param toPath
     */
    public static void backupImages(File fromPath, String toPath) {
        if (fromPath == null && !fromPath.getAbsolutePath().endsWith(".jpg"))
            return;
        BufferedOutputStream os = null;
        FileOutputStream fos = null;
        Bitmap bitmap = null;
        try {
            String src = fromPath.getAbsolutePath();
//			String imgSubStr = src.substring(src.indexOf("image", 0) + 6);
            bitmap = BitmapFactory.decodeFile(src);
//			File file = new File(toPath + imgSubStr);
            File file = new File(toPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            os = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (null != bitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
            System.runFinalization();
        }
    }

    /**
     * 图片按比例大小压缩 根据sd卡获得
     *
     * @param
     * @return
     */
    public static Bitmap getBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        float default_w = 1200.0f;
        float default_h = 900.0f;
        float width = bitmap.getWidth();
        float height = bitmap.getHeight();
        if (width <= default_w && height <= default_h) {
            return bitmap;
        }
        // 计算缩放比例
        float scale = 1;
        float scale1 = (width / height);
        float scale2 = (default_w / default_h);
        if (scale1 > scale2 && width > default_h) {
            scale = default_w / width;
        } else if (scale1 < scale2 && height > default_h) {
            scale = default_h / height;
        } else if (scale1 == scale2) {
            scale = default_h / height;
        }
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        // 得到新的图片
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, (int) width, (int) height, matrix, true);
//        CoreFileUtil.writeFileToPath(CoreFileUtil.logFilePath, bitmap.getByteCount() + "");
        return bitmap;
//        return compressImage(bitmap);
    }

    /**
     * 通过路劲获得图片字节数组,1200*900
     *
     * @param path
     * @return
     */
    public static byte[] getImgByte(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        float default_w = 1200.0f;
        float default_h = 900.0f;
        File file = new File(path);
        if (file.exists()) {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            Bitmap bitMap = BitmapFactory.decodeFile(path, opts);
            float w = opts.outWidth;
            float h = opts.outHeight;
            float be = 1;
            if (w > h && w > default_w) {
                be = (w / default_w);
            } else if (w < h && h > default_h) {
                be = (h / default_h);
            } else if (w == h && w > default_w) {
                be = w / default_w;
            }
            if (be < 0) {
                be = 1;
            }
            opts.inSampleSize = (int) be;
            opts.inJustDecodeBounds = false;
            bitMap = BitmapFactory.decodeFile(path, opts);
            if (bitMap == null) {
                return null;
            }
            float width = bitMap.getWidth();
            float height = bitMap.getHeight();
            if (width <= default_w && height <= default_h) {
                return compressImage2Byte(bitMap);
            }
            // 计算缩放比例
            float scale = 1;
            float scale1 = (width / height);
            float scale2 = (default_w / default_h);
            if (scale1 > scale2 && width > default_h) {
                scale = default_w / width;
            } else if (scale1 < scale2 && height > default_h) {
                scale = default_h / height;
            } else if (scale1 == scale2) {
                scale = default_h / height;
            }
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
            // 得到新的图片
            bitMap = Bitmap.createBitmap(bitMap, 0, 0, (int) width, (int) height, matrix, true);
            return compressImage2Byte(bitMap);
        }
        return null;
    }

    /**
     * 质量压缩，返回byte数组
     *
     * @param image
     * @return
     */
    public static byte[] compressImage2Byte(Bitmap image) {
        if (null == image) {
            return null;
        }
        int options = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        while (baos.toByteArray().length / 1024 > 150 && options > 0) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        image.recycle();
        image = null;
        return baos.toByteArray();
    }

    /**
     * 读取图片 by file
     *
     * @param imagePath
     * @return
     */
    public static Bitmap getBitmapByFile(String imagePath, boolean isScale) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
        // options.inJustDecodeBounds = true;
        // // 获取这个图片的宽和高
        // Bitmap myBitmap = BitmapFactory.decodeFile(imagePath, options); //
        // 此时返回myBitmap为空

        // 计算缩放比
        /*
         * int be = (int) (options.outHeight / (float) 200); int ys =
		 * options.outHeight % 200;// 求余数 float fe = ys / (float) 200; if (fe >=
		 * 0.5) be = be + 1; if (be <= 0) be = 1; if (isScale)
		 * options.inSampleSize = be; // 重新读入图片，注意这次要把options.inJustDecodeBounds
		 * 设为 false options.inJustDecodeBounds = false; myBitmap =
		 * BitmapFactory.decodeFile(imagePath, options);
		 */
        scale = (float) myBitmap.getWidth() / myBitmap.getHeight();
        return myBitmap;
    }

    /**
     * 获取图片 by inputstream
     *
     * @param is
     * @return
     */
    public static Bitmap getBitmapByInputStream(InputStream is) {
        Bitmap bitmap = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            is.close();
            byte[] bytes = out.toByteArray();
            bitmap = getBitmapByBytes(bytes);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        } finally {
            try {
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }
        return bitmap;
    }

    /**
     * 获取图片 by byte[]
     *
     * @param data bytes
     */
    public static Bitmap getBitmapByBytes(byte[] data) {
        // TODO Auto-generated method stub
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, opts);

        opts.inSampleSize = computeSampleSize(opts, -1, 768 * 768);
        opts.inJustDecodeBounds = false;
        try {
            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length,
                    opts);
            return bmp;
        } catch (OutOfMemoryError err) {
            err.printStackTrace();
        }
        return null;
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    /**
     * 计算图片缩放值
     */
    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 转圆角图片
     *
     * @param bitmap 原图
     * @param radis  角度
     * @return
     */
    public static Bitmap creRoundCornerBitmap(Bitmap bitmap, float radis) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = radis;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.WHITE);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 转黑白图片
     *
     * @param bmp
     * @return
     */
    public static Bitmap creBlackWhiteBmp(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();

        ColorMatrix matrix = new ColorMatrix();
        float[] src = {0.308F, 0.609F, 0.082F, 0, 0, 0.308F, 0.609F, 0.082F,
                0, 0, 0.308F, 0.609F, 0.082F, 0, 0, 0, 0, 0, 1, 0};
        matrix.set(src);
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
        Paint p = new Paint();
        p.setColorFilter(filter);
        Bitmap colorBmp = Bitmap.createBitmap(width, height, bmp.getConfig());
        Canvas c = new Canvas(colorBmp);
        c.drawBitmap(bmp, 0, 0, p);
        return colorBmp;
    }

    /**
     * 转 旋转图片
     *
     * @param bmp
     * @param angle 旋转角度
     * @return
     */
    public static Bitmap creRotateBmp(Bitmap bmp, int angle) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
    }

    /**
     * 转 模糊照片
     *
     * @param bmp
     * @param blur 模糊度
     * @return
     */
    public static Bitmap creBlurBitmap(Bitmap bmp, int blur) {

        int pixels[] = new int[bmp.getWidth() * bmp.getHeight()];
        int pixelsRawSource[] = new int[bmp.getWidth() * bmp.getHeight() * 3];
        int pixelsRawNew[] = new int[bmp.getWidth() * bmp.getHeight() * 3];
        bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
                bmp.getHeight());

        for (int k = 1; k <= blur; k++) {

            for (int i = 0; i < pixels.length; i++) {
                pixelsRawSource[i * 3 + 0] = Color.red(pixels[i]);
                pixelsRawSource[i * 3 + 1] = Color.green(pixels[i]);
                pixelsRawSource[i * 3 + 2] = Color.blue(pixels[i]);
            }

            int CurrentPixel = bmp.getWidth() * 3 + 3;
            for (int i = 0; i < bmp.getHeight() - 3; i++) {
                for (int j = 0; j < bmp.getWidth() * 3; j++) {
                    CurrentPixel += 1;

                    int sumColor = 0;
                    sumColor = pixelsRawSource[CurrentPixel - bmp.getWidth()
                            * 3];
                    sumColor = sumColor + pixelsRawSource[CurrentPixel - 3];
                    sumColor = sumColor + pixelsRawSource[CurrentPixel + 3];
                    sumColor = sumColor
                            + pixelsRawSource[CurrentPixel + bmp.getWidth() * 3];
                    pixelsRawNew[CurrentPixel] = Math.round(sumColor / 4);
                }
            }

            for (int i = 0; i < pixels.length; i++) {
                pixels[i] = Color.rgb(pixelsRawNew[i * 3 + 0],
                        pixelsRawNew[i * 3 + 1], pixelsRawNew[i * 3 + 2]);
            }
        }

        Bitmap bmpReturn = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),
                Config.ARGB_8888);
        bmpReturn.setPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
                bmp.getHeight());

        return bmpReturn;
    }

    private final static String TAG = BitmapUtils.class.getSimpleName();


    /**
     * 保存图片到文件中
     *
     * @param bitmap
     * @param path
     */
    public static boolean saveBitmapToFile(Bitmap bitmap, String path) {
        boolean isSuccess = false;
        BufferedOutputStream os = null;
        FileOutputStream fos = null;
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }

            fos = new FileOutputStream(file);
            os = new BufferedOutputStream(fos);

            if (bitmap != null && !bitmap.isRecycled()) {
//                NativeUtil.compressBitmap(bitmap, 85, path, true);
//                if (file.length() == 0) {
//                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
//                }
                bitmap.compress(Bitmap.CompressFormat.JPEG, 85, os);
                if (file.length() == 0) {
                    isSuccess = false;
                }
                isSuccess = true;
            } else {
                isSuccess = false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            isSuccess = false;
        } catch (IOException e) {
            e.printStackTrace();
            isSuccess = false;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                os = null;
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fos = null;
            }
            if (null != bitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
            System.runFinalization();
            return isSuccess;
        }
    }

    private static int getFileNum(File file, String tempPath) {
        String[] fileArr = new File(file.getParent()).list();
        String[] filter = tempPath.split("/");
        String tempArr = filter[filter.length - 1];
        int i = 0;
        for (String str : fileArr) {
            if (str.startsWith(tempArr))
                i++;
        }
        return i;
    }

    /**
     * 将bitmap 转换为 inputStream、
     *
     * @param bitmap
     * @return
     */
    public static InputStream bitmapToInputStream(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        return is;
    }

    /**
     * 判断图片初始宽高比
     */
    public static float scale = 1;

    /**
     * 创建一个缩放的图片
     *
     * @param path 图片地址
     * @param w    图片宽度
     * @param h    图片高度
     * @return 缩放后的图片
     */
    public static Bitmap createBitmap(String path, int w, int h) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            // 这里是整个方法的关键，inJustDecodeBounds设为true时将不为图片分配内存。
            BitmapFactory.decodeFile(path, opts);
            int srcWidth = opts.outWidth;// 获取图片的原始宽度
            int srcHeight = opts.outHeight;// 获取图片原始高度
            scale = (float) srcWidth / srcHeight;
            BlueLog.e("宽高比", "Scale:" + scale);
            int destWidth = 0;
            int destHeight = 0;
            // 缩放的比例
            double ratio = 0.0;
            if (srcWidth < w || srcHeight < h) {
                ratio = 0.0;
                destWidth = srcWidth;
                destHeight = srcHeight;
            } else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小，maxLength是长或宽允许的最大长度
                ratio = (double) srcWidth / w;
                destWidth = w;
                destHeight = (int) (srcHeight / ratio);
            } else {
                ratio = (double) srcHeight / h;
                destHeight = h;
                destWidth = (int) (srcWidth / ratio);
            }
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
            newOpts.inSampleSize = (int) ratio + 1;
            // inJustDecodeBounds设为false表示把图片读进内存中
            newOpts.inJustDecodeBounds = false;
            // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
            newOpts.outHeight = destHeight;
            newOpts.outWidth = destWidth;
            // 获取缩放后图片
            return BitmapFactory.decodeFile(path, newOpts);
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

    /**
     * 根据路径缩放图片
     *
     * @param srcPath
     * @return
     */
    public static Bitmap zoomImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float width = imgWidth == 0.0 ? DEFAULT_IMAGE_WIDTH : imgWidth;
        float height = imgHeight == 0.0 ? DEFAULT_IMAGE_HEIGHT : imgHeight;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > width) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / width);
        } else if (w < h && h > height) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / height);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    /**
     * 根据bitmap缩放图片
     *
     * @param path
     * @return
     */
    public static Bitmap zoomBitmap(String path) {
        try {
            if (TextUtils.isEmpty(path)) {
                return null;
            }
            float default_w = 1200.0f;
            float default_h = 900.0f;
            File file = new File(path);
            if (file.exists()) {
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                Bitmap bitMap = BitmapFactory.decodeFile(path, opts);
                int be = computeSampleSize(opts, -1, (int) (default_w * default_h));
                if (be > 1) {
                    be -= 1;
                }
                opts.inSampleSize = be;
                opts.inJustDecodeBounds = false;
                bitMap = BitmapFactory.decodeFile(path, opts);
                return bitMap;
            }
        } catch (Exception e) {
            if (TextUtils.isEmpty(path)) {
                return null;
            }
            float default_w = 960.0f;
            float default_h = 720.0f;
            File file = new File(path);
            if (file.exists()) {
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                Bitmap bitMap = BitmapFactory.decodeFile(path, opts);
                int be = computeSampleSize(opts, -1, (int) (default_w * default_h));
                opts.inSampleSize = be;
                opts.inJustDecodeBounds = false;
                bitMap = BitmapFactory.decodeFile(path, opts);
                return bitMap;
            }
        }
        return null;
    }

    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 150 && options > 0) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        /**
         * 对可能的OOM做处理
         */
        if (image != null) {
            image.recycle();
            image = null;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = new WeakReference<Bitmap>(BitmapFactory.decodeStream(isBm, null, null)).get();// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }
}
